import { handleDict } from '@/api/ft'

// store/modules/dict.js
const state = {
  dict: {} // 存储所有字典数据的对象
}

// 将获取的字典数据添加到state中
const mutations = {
  SET_DICT: (state, { dictType, data }) => {
    state.dict[dictType] = data
  }
}

const actions = {
  // 获取字典数据（存在则直接返回，不存在则请求）
  getDict({ state, commit }, dictType) {
    return new Promise((resolve, reject) => {
      // 检查是否已存在
      if (state.dict[dictType] && state.dict[dictType].length > 0) {
        resolve(state.dict[dictType])
        return
      }

      // 不存在则请求API
      handleDict({ type: dictType }).then(response => {
        const { data } = response
        commit('SET_DICT', { dictType, data })
        resolve(data)
      }).catch(error => {
        console.error(`获取字典${dictType}失败`, error)
        reject(error)
      })
    })
  }
}

const getters = {
  dict: state => state.dict // 获取所有字典数据
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
